# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/10/17
# @File   : R40_TX_EntConTaxCheck_GZ_XD.py
# @E-mail : zhaochen@bbdservice.com



'''eof
name:企业纳税连续性校验
code:R40_TX_EntConTaxCheck_GZ_XD
tableName:
columnName:
groups:场景业务校验-税务
dependencies:TX_GZ_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import json
import re
import sys
import datetime
import pandas as pd
import math


reload(sys)
sys.setdefaultencoding('utf-8')


def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo


def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_GZ_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]

    except:
        return [{}]

def dataPre(dataList=None, key=None):
    """
    对list里面的列表去重月份不标准的
    :param dataList:
    :param key:
    :return:
    """
    dataListTemp = dataList
    data = []
    for i in range(len(dataListTemp)):
        temp = dataListTemp[i].get(key)
        try:
            temp = int(temp)
        except:
            temp = None
            pass

        if temp:
            data.append(dataListTemp[i])
        else:
            pass

    if len(data) == 0:
        data = [{}]
    else:
        pass

    return data

def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def vatDataMerge(syptZzsxgm, syptZzsybnsr, putBackYear=2, CcrDate=None):
    """
    增值税纳税数据拆分为近两年的月度数据

    :param syptZzsxgm:小规模增值税纳税表[{}]
    :param syptZzsybnsr:一般纳税人增值税表[{}]
    :param putBackYear:回推时间，默认为2年
    :return: VatData为Series
    """

    # 字典排序
    syptZzsybnsr = dataPre(syptZzsybnsr, key='YF')
    syptZzsxgm = dataPre(syptZzsxgm, key='YF')


    # 生成时间轴
    dateIndexList = []
    if CcrDate is None:
        CcrYearMonth = datetime.datetime.now().strftime('%Y-%m-%d')[:7]
        CcrDate = CcrYearMonth + '-01'
        StartDateTmp = str(datetime.datetime.now().year - putBackYear) + CcrDate[4:]
        StartDate = StartDateTmp[:7] + '-01'
    else:
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        CcrDate = convertDataType(CcrDate, 'date_time')[:7] + '-01'
        StartDate = str(CcrYear - putBackYear) + convertDataType(CcrDate, 'date_time')[4:]

    dateSet = pd.date_range(StartDate, CcrDate, freq='M')
    for i in dateSet:
        year = i.date().year
        month = i.date().month
        dateIndexList.append(str(year)+str(month))

    VatData = pd.Series(None, index=dateIndexList)

    if syptZzsxgm == [{}] and syptZzsybnsr == [{}]:
        return VatData
    else:
        # 一般纳税人
        if syptZzsybnsr != [{}]:
            syptZzsybnsr = sorted(syptZzsybnsr, key=lambda x: int(x['YF']))
            for i in range(len(syptZzsybnsr)):
                ND = convertDataType(syptZzsybnsr[i].get('ND'), 'int')
                YF = convertDataType(syptZzsybnsr[i].get('YF'), 'int')
                if ND and YF:
                    NDYF = str(ND) + str(YF)
                    if NDYF in VatData.index:
                        YNSEHJ = convertDataType(syptZzsybnsr[i].get('YNSEHJ'), 'float')
                        if YNSEHJ is not None:
                            if math.isnan(VatData.loc[str(ND) + str(YF)]):
                                VatData.loc[str(ND) + str(YF)] = YNSEHJ
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
                else:
                    pass

        # 小规模纳税人
        if syptZzsxgm != [{}]:
            syptZzsxgm = sorted(syptZzsxgm, key=lambda x: int(x['YF']))
            for i in range(len(syptZzsxgm)):
                ND = convertDataType(syptZzsxgm[i].get('ND'), 'int')
                YF = convertDataType(syptZzsxgm[i].get('YF'), 'int')
                if ND and YF:
                    NDYF = str(ND) + str(YF)
                    if NDYF in VatData.index:
                        YNSEHJDBNBQ = convertDataType(syptZzsxgm[i].get('YNSEHJDBNBQ'), 'float')
                        if YNSEHJDBNBQ is not None:
                            if YF not in [3, 6, 9, 12]:
                                if math.isnan(VatData.loc[str(ND)+str(YF)]):
                                    VatData.loc[str(ND)+str(YF)] = YNSEHJDBNBQ
                            else:
                                # 倒推三个月在时间轴内
                                if ((str(ND) + str(YF)) in VatData.index) and ((str(ND) + str(YF-1)) in VatData.index) and\
                                        ((str(ND) + str(YF-2)) in VatData.index):

                                    # 临近三个月全为空，3个为空
                                    if math.isnan(VatData.loc[str(ND) + str(YF)]) \
                                            and math.isnan(VatData.loc[str(ND) + str(YF - 1)])\
                                            and math.isnan(VatData.loc[str(ND) + str(YF - 2)]):
                                        VatData.loc[str(ND) + str(YF)] = YNSEHJDBNBQ / 3
                                        VatData.loc[str(ND) + str(YF - 1)] = YNSEHJDBNBQ / 3
                                        VatData.loc[str(ND) + str(YF - 2)] = YNSEHJDBNBQ / 3
                                    # 临近三个月倒数第3个月非空，2个为空
                                    elif math.isnan(VatData.loc[str(ND) + str(YF - 1)]) and \
                                            not math.isnan(VatData.loc[str(ND) + str(YF - 2)]):
                                        VatData.loc[str(ND) + str(YF - 1)] = YNSEHJDBNBQ / 2
                                        VatData.loc[str(ND) + str(YF)] = YNSEHJDBNBQ / 2
                                    # 临近三个月倒数第2个月非空，2个为空
                                    elif math.isnan(VatData.loc[str(ND) + str(YF - 2)]) and \
                                        not math.isnan(VatData.loc[str(ND) + str(YF - 1)]):
                                        VatData.loc[str(ND) + str(YF - 2)] = YNSEHJDBNBQ / 2
                                        VatData.loc[str(ND) + str(YF)] = YNSEHJDBNBQ / 2
                                    # 临近三个月倒数第三个月非空，1个为空
                                    elif not math.isnan(VatData.loc[str(ND) + str(YF - 2)]) and \
                                        not math.isnan(VatData.loc[str(ND) + str(YF - 1)]) \
                                            and math.isnan(VatData.loc[str(ND) + str(YF)]):
                                        VatData.loc[str(ND) + str(YF)] = YNSEHJDBNBQ
                                # 倒数最后YF-2月不在时间轴内
                                elif (str(ND) + str(YF-2)) not in VatData.index and ((str(ND) + str(YF)) in VatData.index) and\
                                        ((str(ND) + str(YF-1)) in VatData.index):
                                    # 倒推两个月都为空
                                    if math.isnan(VatData.loc[str(ND) + str(YF)]) and math.isnan(VatData.loc[str(ND) + str(YF-1)]):
                                        VatData.loc[str(ND) + str(YF)] = YNSEHJDBNBQ / 3
                                        VatData.loc[str(ND) + str(YF - 1)] = YNSEHJDBNBQ / 3
                                    elif math.isnan(VatData.loc[str(ND) + str(YF-1)]):
                                        VatData.loc[str(ND) + str(YF)] = YNSEHJDBNBQ / 2
                                # 倒数YF-1月不在时间轴内
                                elif str(ND) + str(YF-1) not in VatData.index and (str(ND) + str(YF-2)) not in VatData.index and\
                                        ((str(ND) + str(YF)) in VatData.index):
                                    if math.isnan(VatData.loc[str(ND) + str(YF)]):
                                        VatData.loc[str(ND) + str(YF)] = YNSEHJDBNBQ / 3
                        else:
                            pass
                    else:
                        pass
                else:
                    pass

    return VatData



def incomeTaxDataMerge(syptQysdsNd, syptQysdsA1, putBackYear=2, CcrDate=None):
    """
    所得税纳税数据拆分为近2年的月度数据

    :param syptQysdsNd: 年度汇算清缴表，类型[{}]
    :param syptQysdsA1: A1表，类型[{}]
    :param putBackYear: 回推时间，默认为2年
    :return: IncomeTaxData为Series
    """
    # 字典排序
    syptQysdsNd = dataPre(syptQysdsNd, key='ND')
    syptQysdsA1 = dataPre(syptQysdsA1, key='YF')


    # 生成时间轴
    dateIndexList = []
    if CcrDate is None:
        CcrYearMonth = datetime.datetime.now().strftime('%Y-%m-%d')[:7]
        CcrDate = CcrYearMonth + '-01'
        StartDateTmp = str(datetime.datetime.now().year - putBackYear) + CcrDate[4:]
        StartDate = StartDateTmp[:7] + '-01'
    else:
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        CcrDate = convertDataType(CcrDate, 'date_time')[:7] + '-01'
        StartDate = str(CcrYear - putBackYear) + convertDataType(CcrDate, 'date_time')[4:]

    dateSet = pd.date_range(StartDate, CcrDate, freq='M')
    for i in dateSet:
        year = i.date().year
        month = i.date().month
        dateIndexList.append(str(year) + str(month))

    IncomeTaxData = pd.Series(None, index=dateIndexList)

    if syptQysdsNd == [{}] and syptQysdsA1 == [{}]:
        return IncomeTaxData
    else:
        # 使用年度汇算清缴表
        if syptQysdsNd != [{}]:
            syptQysdsNd = sorted(syptQysdsNd, key=lambda x: int(x['ND']))
            for i in range(len(syptQysdsNd)):
                ND = convertDataType(syptQysdsNd[i].get('ND'), 'int')
                NDYF = [str(datetime.datetime.now().year-1),
                        str(datetime.datetime.now().year-2),
                        str(datetime.datetime.now().year-3)]
                if ND and str(ND) in NDYF:
                    YNSDSE = convertDataType(syptQysdsNd[i].get('YNSDSE'), 'float')
                    if YNSDSE is not None:
                        for j in IncomeTaxData.index:
                            if str(ND) in j and math.isnan(IncomeTaxData.loc[j]):
                                IncomeTaxData.loc[j] = YNSDSE/12
                            else:
                                pass
                    else:
                        pass
                else:
                    pass

        # 使用A1表(默认为只有按季度缴纳)
        if syptQysdsA1 != [{}]:
            syptQysdsA1 = sorted(syptQysdsA1, key=lambda x: int(x['YF']))
            for i in range(len(syptQysdsA1)):
                ND = convertDataType(syptQysdsA1[i].get('ND'), 'int')
                YF = convertDataType(syptQysdsA1[i].get('YF'), 'int')
                if ND and YF:
                    NDYF = str(ND) + str(YF)
                    if NDYF in IncomeTaxData.index:
                        YNSSDE = convertDataType(syptQysdsA1[i].get('YNSSDE'), 'float')
                        if YF in [3, 6, 9, 12]:
                            if YNSSDE is not None:
                                # 倒推三个月在时间轴内
                                if ((str(ND) + str(YF)) in IncomeTaxData.index) and ((str(ND) + str(
                                        YF - 1)) in IncomeTaxData.index) and \
                                        ((str(ND) + str(YF - 2)) in IncomeTaxData.index):

                                    # 临近三个月全为空，3个为空
                                    if math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]) \
                                            and math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]) \
                                            and math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 3
                                        IncomeTaxData.loc[str(ND) + str(YF - 1)] = YNSSDE / 3
                                        IncomeTaxData.loc[str(ND) + str(YF - 2)] = YNSSDE / 3
                                    # 临近三个月倒数第3个月非空，2个为空
                                    elif math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]) and \
                                            not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]):
                                        IncomeTaxData.loc[str(ND) + str(YF - 1)] = YNSSDE / 2
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 2
                                    # 临近三个月倒数第2个月非空，2个为空
                                    elif math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]) and \
                                            not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]):
                                        IncomeTaxData.loc[str(ND) + str(YF - 2)] = YNSSDE / 2
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 2
                                    # 临近三个月倒数第三个月非空，1个为空
                                    elif not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]) and \
                                            not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]) \
                                            and math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE
                                # 倒数最后二个月不在时间轴内
                                elif (str(ND) + str(YF - 2)) not in IncomeTaxData.index and\
                                        ((str(ND) + str(YF - 1)) in IncomeTaxData.index) and ((str(ND) + str(
                                        YF)) in IncomeTaxData.index):
                                    # 倒推两个月都为空
                                    if math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]) and math.isnan(
                                            IncomeTaxData.loc[str(ND) + str(YF - 1)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 3
                                        IncomeTaxData.loc[str(ND) + str(YF - 1)] = YNSSDE / 3
                                    elif math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 2
                                # 倒数最后一个月不在时间轴内
                                elif (str(ND) + str(YF - 2)) not in IncomeTaxData.index and \
                                        ((str(ND) + str(YF - 1)) not in IncomeTaxData.index) and ((str(ND) + str(
                                        YF)) in IncomeTaxData.index):
                                    if math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 3
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
                else:
                    pass

        return IncomeTaxData

def incomeTaxCon(syptQysdsNd, syptQysdsA1,putBackYear=2, CcrDate=None):
    """
    所得税连续性纳税情况

    :param syptQysdsNd: 年度汇算清缴表，类型[{}]
    :param syptQysdsA1: A1表，类型[{}]
    :param putBackYear: 回推时间，默认为2年
    :return: Factor3, Factor4
    """
    # 字典排序
    syptQysdsNd = dataPre(syptQysdsNd, key='ND')

    # 生成时间轴
    dateIndexList = []
    if CcrDate is None:
        CcrYearMonth = datetime.datetime.now().strftime('%Y-%m-%d')[:7]
        CcrDate = CcrYearMonth + '-01'
        StartDateTmp = str(datetime.datetime.now().year - putBackYear) + CcrDate[4:]
        StartDate = StartDateTmp[:7] + '-01'
    else:
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        CcrDate = convertDataType(CcrDate, 'date_time')[:7] + '-01'
        StartDate = str(CcrYear - putBackYear) + convertDataType(CcrDate, 'date_time')[4:]

    dateSet = pd.date_range(StartDate, CcrDate, freq='M')
    for i in dateSet:
        year = i.date().year
        month = i.date().month
        dateIndexList.append(str(year) + str(month))

    IncomeTaxData = pd.Series(None, index=dateIndexList)

    if syptQysdsNd == [{}]:
        Factor3 = 0
        Factor4 = 0
        return Factor3, Factor4
    # 如果A1表不存在,仅有年度汇算清缴表
    else:
        syptQysdsNd = sorted(syptQysdsNd, key=lambda x: int(x['ND']))

        Factor3 = 0
        Factor4 = 0
        CcrMonth = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().month
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        syptQysdsNdSeries = pd.DataFrame(syptQysdsNd).dropna(how='all')

        # 申请月小于等于5月
        if CcrMonth <= 5:
            # 如果申请年-1数据存在
            if str(CcrYear-1) in list(syptQysdsNdSeries['ND']):
                if convertDataType(syptQysdsNdSeries[syptQysdsNdSeries['ND'] == str(CcrYear-1)]['YNSDSE'].iloc[-1], 'float'):
                    Factor4 = 1

                else:
                    if str(CcrYear - 2) in list(syptQysdsNdSeries['ND']):
                        if convertDataType(syptQysdsNdSeries[syptQysdsNdSeries['ND'] == str(CcrYear - 2)]['YNSDSE'].iloc[-1], 'float'):
                            Factor4 = 1
                        else:
                            Factor4 = 0
                    else:
                        Factor4 = 0

            # 如果申请年-1不存在
            else:
                if str(CcrYear-2) in list(syptQysdsNdSeries['ND']):
                    if convertDataType(syptQysdsNdSeries[syptQysdsNdSeries['ND'] == str(CcrYear-2)]['YNSDSE'].iloc[-1], 'float'):
                        Factor4 = 1
                    else:
                        Factor4 = 0
                else:
                    Factor4 = 0
        # 申请月大于6月
        else:
            if str(CcrYear-1) in list(syptQysdsNdSeries['ND']):
                if convertDataType(syptQysdsNdSeries[syptQysdsNdSeries['ND'] == str(CcrYear - 1)]['YNSDSE'].iloc[-1], 'float'):
                    Factor4 = 1
                else:
                    Factor4 = 0
            else:
                Factor4 = 0

    return Factor3, Factor4



def entConTaxCheck(spDate=None):
    """
    连续性纳税校验
    :return:
    """

    syptSwdjxx = formatData('syptSwdjxx')
    syptQysdsNd = formatData('syptQysdsNd')
    syptQysdsA1 = [{}]
    syptZzsxgm = formatData('syptZzsXgm')
    syptZzsybnsr = formatData('syptZzsybnsr')

    if syptSwdjxx == [{}]:
        return u'缺失值'
    else:
        NSRZG_DM = convertDataType(syptSwdjxx[0].get('NSRZG_DM'), 'str')

        # 增值税合并数据
        if syptQysdsA1 == [{}] and syptQysdsNd == [{}] and syptZzsxgm == [{}] and syptZzsybnsr == [{}]:
            return u'缺失值'
        else:
            vatSeries = vatDataMerge(syptZzsxgm=syptZzsxgm, syptZzsybnsr=syptZzsybnsr, CcrDate=spDate, putBackYear=1)

        # 增值税缴纳连续性判断
        # 小规模
        if NSRZG_DM in ['204', '205']:
            Factor1 = len(vatSeries.dropna(how='all'))
            Factor2 = 0
        # 其他纳税人
        else:
            Factor2 = len(vatSeries.dropna(how='all'))
            Factor1 = 0

        # 所得税数据缴纳情况
        if syptQysdsA1 == [{}] and syptQysdsNd == [{}] and syptZzsxgm == [{}] and syptZzsybnsr == [{}]:
            return u'缺失值'
        else:
            Factor3, Factor4 = incomeTaxCon(syptQysdsNd=syptQysdsNd, syptQysdsA1=syptQysdsA1, CcrDate=spDate)

        # 逻辑判断
        if Factor1 >= 9 or Factor2 >= 11 or Factor4 >= 1:
            Factor = 1
        else:
            Factor = 0


        return Factor


result = entConTaxCheck()
